package com.mg;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class SubReqServerHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        SubScribeReqProto.SubScribeReq req = (SubScribeReqProto.SubScribeReq) msg;
        if ("fiver".equals(req.getUserName())) {
            System.out.println("Service accept client subscribe req：[" + req.toString() + "]");
            ctx.writeAndFlush(resp(req.getSubReqID()));
        }
    }

    private SubScribeRespProto.SubScribeResp resp(int subReqID) {
        SubScribeRespProto.SubScribeResp.Builder builder = SubScribeRespProto.SubScribeResp.newBuilder();
        builder.setSubReqID(subReqID);
        builder.setRespCode(0);
        builder.setDesc("Netty book order succeed !!");
        return builder.build();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}